<script setup lang="ts">
import type { ConditionField, IConditionGroup, Option } from './typing'
import ConditionGroup from './ConditionGroup.vue'
import { defaultOperations, defaultRelations, defaultValue } from './typing'

defineOptions({
  name: 'ConditionBuilder',
})

const props = withDefaults(defineProps<{
  fields: ConditionField[]
  value?: IConditionGroup
  defaultOperations?: Option[]
  defaultRelations?: Option[]
}>(), {
  value: () => defaultValue,
  defaultOperations: () => defaultOperations,
  defaultRelations: () => defaultRelations,
})

const emit = defineEmits<{
  'update:value': [value: IConditionGroup]
}>()

provide<ConditionField[]>('fields', props.fields)
provide<Option[]>('defaultOperations', props.defaultOperations)
provide<Option[]>('defaultRelations', props.defaultRelations)

const model = ref<IConditionGroup>({ ...props.value })

watch(
  () => props.value,
  (val) => {
    Object.assign(model.value, val)
  },
  { deep: true, immediate: true },
)

watch(
  () => model.value,
  (val) => {
    emit('update:value', val)
  },
  { deep: true, immediate: true },
)

function validate(group = model.value): boolean {
  // 校验单个条件
  function checkCondition(cond: any) {
    return !!(cond.key && cond.operator && cond.value)
  }
  // 递归校验组
  function checkGroup(g: any): boolean {
    if (!g.children || !Array.isArray(g.children))
      return true
    return g.children.every((child: IConditionGroup) =>
      child.children ? checkGroup(child) : checkCondition(child),
    )
  }
  return checkGroup(group)
}

defineExpose({ validate })
</script>

<template>
  <div class="condition-builder">
    <ConditionGroup v-model:value="model" />
  </div>
</template>

<style scoped>
.condition-builder {
  width: 100%;
  /* 线的大小 */
  --line-size: 2px;
  /* 间距 */
  --gap: 12px;
  /* 线的颜色 */
  --line-color: rgba(0, 0, 0, 0.1);
  --bg-color: #fff;
}

.dark .condition-builder {
  --line-color: rgba(255, 255, 255, 0.1);
  --bg-color: #18181c;
}
</style>
